/*
 * Created on 2005/4/3
 *
 */
package br.com.wai2008.client.presentation;

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Panel;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.ImageObserver;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JTextField;

import br.com.wai2008.client.configurations.ClientConfigurations;
import br.com.wai2008.client.constants.ClientConstants;
import br.com.wai2008.client.dataobject.WAILocalizationObject;
import br.com.wai2008.client.dataobject.WAIServiceObject;

/**
 * @author André Romero Gonçales
 *  
 */
public class WAI2008ServiceMap extends Panel {

	private static final long serialVersionUID = 5098607502238613114L;
	WAI2008Interface app;
    CanvasMap canvas;
    
    private boolean simulation = false;
    
    private String target = ClientConstants.getTarget(ClientConstants.TARGET_0);
    
    private int restriction = 0;
    
    private int floor = 0;
    
    private String language = "PtBr";
    
    private List<WAILocalizationObject> simulatedPositions = new ArrayList<WAILocalizationObject>();
    
    private boolean start = false;
    
    private JTextField pointText = new JTextField("0   ");

	private JTextField xText = new JTextField("0       ");
    
    private JTextField yText = new JTextField("0       ");
    
    private JTextField floorText = new JTextField("0   ");
    
    public JTextField getPointText() {
		return pointText;
	}
    
    public int getPointNumber() {
    	return this.simulatedPositions.size();
    }

	public void setPointText(String pointText) {
		this.pointText.setText(pointText);
	}

	public JTextField getXText() {
		return xText;
	}

	public void setXText(String text) {
		xText.setText(text);
	}

	public JTextField getYText() {
		return yText;
	}

	public void setYText(String text) {
		yText.setText(text);
	}

	public JTextField getFloorText() {
		return floorText;
	}

	public void setFloorText(String floorText) {
		this.floorText.setText(floorText);
	}
    
    public boolean isStarted() {
    	return this.start;
    }

	public void start() {
		this.start = true;
	}

	public void stop() {
		this.start = false;
		this.resetSimulatedPositions();
	}

	public void resetSimulatedPositions() {
		this.simulatedPositions = new ArrayList<WAILocalizationObject>();
	}
	
	public void addSimulatedPosition(WAILocalizationObject object) {
		this.simulatedPositions.add(object);
	}
	
	public WAILocalizationObject removeFirstSimulatedPosition() {
		if (this.simulatedPositions.size() > 0) {
			WAILocalizationObject object = this.simulatedPositions.remove(0);
			return object;
		} else {
			return null;
		}
	}

	public String getTarget() {
		return target;
	}

	public void setTarget(String target) {
		this.target = target;
	}

	public boolean isSimulation() {
		return simulation;
	}

	public void setSimulation(boolean simulation) {
		this.simulation = simulation;
	}

	public WAI2008ServiceMap(WAI2008Interface _app) {
        app = _app;
        setLayout(new BorderLayout());
        add(canvas = new CanvasMap(app, this));
        setBounds(25, 0, WAI2008Interface.APP_W, WAI2008Interface.APP_H - 25);
    }

    public CanvasMap getCanvas() {
        return canvas;
    }

	public int getRestriction() {
		return restriction;
	}

	public void setRestriction(int restriction) {
		this.restriction = restriction;
	}

	public int getFloor() {
		return floor;
	}

	public void setFloor(int floor) {
		this.floor = floor;
	}

	public String getLanguage() {
		return language;
	}

	public void setLanguage(String language) {
		this.language = language;
	}

}

class CanvasMap extends Canvas implements ImageObserver, MouseListener, MouseMotionListener, Runnable {

    /**
	 * 
	 */
	private static final long serialVersionUID = -1397625161770562915L;
    private int contadorBolaAtual = 0;

    WAI2008Interface app;
	private WAI2008ServiceMap map;
    Image img;
    
    double hmult = 0.8;
    int xprev = 0;
    int yprev = 0;
    int xpos = 0;
    int ypos = 0;

    boolean isCentralizacaoAutomatica = true;

    WAIServiceObject service = null;

    public CanvasMap(WAI2008Interface _app, WAI2008ServiceMap map) {
        app = _app;
        this.map = map;
        setBounds(0, 0, 240, 295);
        addMouseListener(this);
        addMouseMotionListener(this);
        new Thread(this).start();
    }

    public void mouseClicked(MouseEvent e) {
    	if (map.isSimulation() && this.isCentralizacaoAutomatica) {
    		WAILocalizationObject object = new WAILocalizationObject(new Double(e.getX()/hmult - xpos).intValue(), 
    				new Double(e.getY()/hmult - ypos).intValue(), 0);
    		map.addSimulatedPosition(object);
    		map.setPointText("" + map.getPointNumber());
    		map.setXText("" + new Double(e.getX()/hmult - xpos).intValue());
    		map.setYText("" + new Double(e.getY()/hmult - ypos).intValue());
            //System.out.println("clicou no mapa posicao: " + e.getX() + " , " + e.getY());
            //System.out.println("clicou no mapa posicao: " + (e.getX()/hmult - xpos) + " , " + (e.getY()/hmult - ypos));
    		System.out.println("" + map.getPointNumber() + "      " + new Double(e.getX()/hmult - xpos).intValue() 
    				+ "      " + new Double(e.getY()/hmult - ypos).intValue());
            
    	} else if (!map.isSimulation() && this.isCentralizacaoAutomatica) {
			this.printFile(new Double(e.getX()/hmult - xpos).intValue(), new Double(e.getY()/hmult - ypos).intValue());
    	}
    }   

	private void printFile(int x, int y) {
		try {
			File file  = new File("/romeroWorkspace/Logs/Trajetoria.txt");
			BufferedWriter buffer = new BufferedWriter(new FileWriter(file, true));
			Date date = new Date();
			buffer.write(date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "\t");			
			buffer.write(x + "\t" + y);
			buffer.write("\n");
			buffer.flush();
			buffer.close();
			
		} catch (FileNotFoundException e) {
			System.out.println("ERROR: Arquivo para LOG nao encontrado;");
		} catch (IOException e) {
			System.out.println("ERROR: Arquivo para LOG nao encontrado;");
		}
	}

    public void mouseEntered(MouseEvent e) {
        requestFocus();
        e.consume();
    }

    public void mouseExited(MouseEvent e) {
    }

    public void mousePressed(MouseEvent e) {
        xprev = e.getX();
        yprev = e.getY();
        //		System.out.println("precionou no mapa posicao: " + e.getX() + " , " +
        // e.getY());
        //		System.out.println("ImgWidth=" + img.getWidth(app) + " ImgHeight=" +
        // img.getHeight(app) );
        e.consume();
    }

    public void mouseReleased(MouseEvent e) {
        e.consume();
    }

    public void mouseDragged(MouseEvent e) {
        int xMouse = e.getX();
        int yMouse = e.getY();

        if (!isCentralizacaoAutomatica) {
            xpos += xMouse - xprev;
            ypos += yMouse - yprev;
            ajustaXPosYPos();
        }

        xprev = xMouse;
        yprev = yMouse;
        e.consume();
    }

    public void mouseMoved(MouseEvent e) {
    }

    public void paint(Graphics g) {
		g.drawImage(img, xpos, ypos, (int) (img.getWidth(this) * hmult), (int) (img.getHeight(this) * hmult), this);
        g.setColor(Color.red);

        if (service != null && service.getRoute() != null) {
            for (int i = 0; i < service.getRoute().length - 1; i++) {
                g.drawLine((int) (((WAILocalizationObject) service.getRoute()[i]).getX() * hmult + xpos),
                        (int) (((WAILocalizationObject) service.getRoute()[i]).getY() * hmult + ypos), (int) (((WAILocalizationObject) service.getRoute()[i+1]).getX()
                                * hmult + xpos), (int) (((WAILocalizationObject) service.getRoute()[i+1]).getY() * hmult + ypos));
            }
            g.setColor(Color.orange);
            int raio = contadorBolaAtual * 3;
            g.drawOval((int) (service.getRoute()[0].getX() * hmult + xpos) - raio,
                    (int) (service.getRoute()[0].getY() * hmult + ypos) - raio, raio * 2, raio * 2);
        }
    }

    public void ampliar() {
        hmult *= 1.2;
        ajustaXPosYPos();
    }

    public void diminuir() {
        hmult /= 1.2;
        ajustaXPosYPos();
    }

    public void alteraCentralizacaoAutomatica() {
        isCentralizacaoAutomatica = !isCentralizacaoAutomatica;
    }

    private void ajustaXPosYPos() {
        int xLimiteMax = img.getWidth(app) * hmult > getBounds().width ? 0 : (int) (getBounds().width - img
                .getWidth(app)
                * hmult);
        int xLimiteMin = img.getWidth(app) * hmult > getBounds().width ? (int) (getBounds().width - img.getWidth(app)
                * hmult) : 0;
        int yLimiteMax = img.getHeight(app) * hmult > getBounds().height ? 0 : (int) (getBounds().height - img
                .getHeight(app)
                * hmult);
        int yLimiteMin = img.getHeight(app) * hmult > getBounds().height ? (int) (getBounds().height - img
                .getHeight(app)
                * hmult) : 0;

        if (xpos > xLimiteMax)
            xpos = xLimiteMax;
        if (xpos < xLimiteMin)
            xpos = xLimiteMin;
        if (ypos > yLimiteMax)
            ypos = yLimiteMax;
        if (ypos < yLimiteMin)
            ypos = yLimiteMin;

        repaint();
    }

    public void run() {
        img = app.getImage(app.getDocumentBase(), "br/com/wai2008/client/presentation/Andar" + 0 + ".PNG");
        //img = app.getImage(app.getDocumentBase(), "br/com/wai2008/client/presentation/Andar0_pontos_numerados_teste2.PNG");
        
        Date date = new Date();

    	this.service = Service.service;
        while (true) {
        	if (map.isStarted()) {
	            contadorBolaAtual = ++contadorBolaAtual % 15;
	            Date date2 = new Date();
	            if (map.isStarted() && !map.isSimulation() && 
	            		(date2.getTime() - date.getTime()) > ClientConfigurations.TIME_BETWEEN_MEASURE) {
	            	new Service(service, app, map).start();
	            	date = date2;
	            } else if (map.isStarted() && map.isSimulation() && 
	            		(date2.getTime() - date.getTime()) > ClientConfigurations.TIME_BETWEEN_SIMULATION_MEASURE){
	            	new Service(service, app, map).start();
	            	date = date2;
	            }
	        	this.service = Service.service;
	            repaint();
	            try {
	                Thread.sleep(ClientConfigurations.REFRESH_SCREEN);
	            } catch (InterruptedException e) {
	            }
        	}
        }
    }

    public boolean isCentralizacaoAutomatica() {
        return isCentralizacaoAutomatica;
    }

}

class Service extends Thread {

	public static WAIServiceObject service;
	private WAI2008Interface app;
	private WAI2008ServiceMap map;
	
	Service (WAIServiceObject object, WAI2008Interface app, WAI2008ServiceMap map) {
		service = object;
		this.app = app;
		this.map = map;
	}
	
	public void run() {
		if (map.isSimulation()) {
			WAILocalizationObject object = map.removeFirstSimulatedPosition();
			if (object != null) {
				service = app.getService().obterRota(map.getTarget(), object, map.getFloor(), map.getRestriction(),
						map.getLanguage(), map.isSimulation());
			}
		} else {
			System.out.println("here");
			service = app.getService().obterRota(map.getTarget(), null, map.getFloor(), map.getRestriction(),
					map.getLanguage(), map.isSimulation());
		}
		
	}
	
}